<template>
  <div class="app-container">
    <!-- 查询框 -->
    <search-bar class="search">
      <template slot="peopleSearch">
        <el-form class="form">
          <el-row type="flex" justify="end">
            <el-form-item>
              <el-col>
                <div>型号搜索:</div>
              </el-col>
            </el-form-item>
            <el-form-item>
              <el-col :span="26">
                <el-input
                  v-model="value"
                  class="input"
                  placeholder="请输入"
                  clearable
                />
              </el-col>
            </el-form-item>
            <el-form-item>
              <el-col class="InquireBtn" :push="3">
                <el-button class="InquireBtn" @click="searchBtn">
                  <i class="el-icon-search" />查询</el-button>
              </el-col>
            </el-form-item>
          </el-row>
        </el-form>
      </template>
    </search-bar>
    <!-- 表格表单 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button class="addBtn" @click="isShowDialog = true">
            <!-- 新增按钮 -->
            <i class="el-icon-circle-plus-outline" /> 新增</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="vmTypeList"
        stripe
        style="width: 100%; padding-top: 20px"
        :header-cell-style="{
          color: '#333744',
          background: 'rgb(243, 246, 251)',
        }"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column prop="name" label="型号名称" />
        <el-table-column prop="model" label="型号编码" />
        <el-table-column prop="image" label="设备图片">
          <template
            v-slot="{ row }"
          ><img :src="row.image" class="img">
          </template>
        </el-table-column>
        <el-table-column prop="vmRow" label="货道行" />
        <el-table-column prop="vmCol" label="货道列" />
        <el-table-column prop="channelMaxCapacity" label="设备容量" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              type="text"
              size="small"
              @click="editShowDialog(row.typeId)"
            >修改</el-button>
            <el-button
              type="text"
              size="small"
              style="color: red"
              @click="delBtn(row.typeId)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination
          layout="prev, pager, next"
          prev-text="上一页"
          next-text="下一页"
          :page-size="pageConfig.size"
          :current-page="pageConfig.page"
          :total="total"
          @current-change="changePage"
        />
      </el-row>
    </el-card>
    <!-- 弹框 -->
    <el-dialog
      :title="`${vmList.typeId ? '编辑' : '新增'}设备类型`"
      :visible="isShowDialog"
      @close="btnDelete"
    >
      <el-form ref="form" label-width="120px" :rules="rules" :model="vmList">
        <el-form-item label="型号名称" prop="name">
          <el-input
            v-model="vmList.name"
            style="width: 88%"
            label="请输入"
            placeholder="请输入"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="型号编码" prop="model">
          <el-input
            v-model="vmList.model"
            style="width: 88%"
            placeholder="请输入(限制数字、字母、中划线、下划线)"
            maxlength="15"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="货道行数" prop="vmRow">
          <el-input-number
            v-model="vmList.vmRow"
            style="width: 88%"
            controls-position="right"
            :min="1"
            :max="10"
          />
        </el-form-item>
        <el-form-item label="货到列数" prop="vmCol">
          <el-input-number
            v-model="vmList.vmCol"
            style="width: 88%"
            controls-position="right"
            :min="1"
            :max="10"
          />
        </el-form-item>
        <el-form-item label="货道容量" prop="channelMaxCapacity">
          <el-input-number
            v-model="vmList.channelMaxCapacity"
            style="width: 88%"
            controls-position="right"
            :min="1"
            :max="10"
          />
        </el-form-item>
        <el-form-item label="设备图片" prop="image">
          <el-upload
            action="https://jsonplaceholder.typicode.com/posts/"
            list-type="picture-card"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="imageUrl"
              v-imgError
              :src="imageUrl"
              class="avatar"
            >
            <i v-else class="el-icon-plus" /></el-upload>
          <span>支持扩展名：jpg、png，文件不得大于100kb</span>
        </el-form-item>
      </el-form>
      <!-- footer插槽 -->
      <template>
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnDelete">取消</el-button>
            <el-button
              type="primary"
              size="small"
              @click="btnOK"
            >确定</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getSearchVmType, getVmType, reviseVmType } from '@/api/goods'
import { DelVmType, getVmNewType } from '@/api/table'
import { imageSave } from '@/api/user'
export default {
  data() {
    const checkRepeatModel = async(rule, val, callback) => {
      const { data } = await getSearchVmType()
      const Newres = data.currentPageRecords.find((item) => item.model === val)
      if (Newres && Newres.typeId !== this.vmList.typeId) {
        callback(new Error('编号不能重复'))
      } else {
        callback
      }
    }
    return {
      vmTypeList: [],
      isShowDialog: false,
      pageConfig: {
        pageIndex: 1,
        pageSize: 10
      },
      total: 0,
      value: '',
      vmList: {
        name: '',
        model: '',
        vmRow: '',
        vmCol: '',
        channelMaxCapacity: '',
        image: ''
      },
      searchList: [],
      imageUrl: '',
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        model: [
          { required: true, message: '请输入', trigger: 'blur' },
          {
            pattern: /^[A-Za-z0-9_-]+$/,
            message: '请输入正确的型号编码',
            trigger: 'blur'
          },
          { min: 1, max: 15, message: '请输入正确的型号编码' },
          { trigger: 'blur', validator: checkRepeatModel }
        ],
        image: [
          { required: true, message: '请添加图片', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getVmType()
  },
  methods: {
    // 编辑弹框
    async editShowDialog(typeId) {
      const res = await getVmType(typeId)
      this.isShowDialog = true
      this.vmList = res.data
      this.imageUrl = res.data.image
    },
    // 列表渲染
    async getVmType() {
      const res = await getSearchVmType(this.pageConfig)
      this.vmTypeList = res.data.currentPageRecords
      this.total = +res.data.totalCount
    },
    // 分页
    async changePage(newPage) {
      this.pageConfig.pageIndex = newPage
      await this.getVmType()
    },
    // 取消按钮
    async delBtn(typeId) {
      await this.$confirm('确认删除这条信息吗')
      await DelVmType(typeId)
      this.$message.success('恭喜删除成功')
      this.getVmType()
    },
    // 搜索按钮
    async searchBtn() {
      const obj = {
        pageIndex: 1,
        pageSize: 999,
        name: this.value.trim()
      }
      const res = await getSearchVmType(obj)
      this.searchList = res.data.currentPageRecords
      this.vmTypeList = this.searchList
    },
    // 确认按钮
    async btnOK() {
      await this.$refs.form.validate()
      this.vmList.typeId
        ? await reviseVmType(this.vmList)
        : await getVmNewType(this.vmList)
      this.$message.success('操作成功')
      this.isShowDialog = false
      this.getVmType()
    },
    // 取消按钮
    async btnDelete() {
      this.vmList = {
        name: '',
        model: '',
        vmRow: '',
        vmCol: '',
        channelMaxCapacity: '',
        image: ''
      }
      this.imageUrl = ''
      this.$refs.form.resetFields()
      this.isShowDialog = false
    },
    // 控制格式
    async handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      // 创建form表单对象，用于上传图像的数据操作
      const formData = new FormData()
      // 将图像文件的名称添加到表单中
      formData.append('fileName', file.raw)
      const files = await imageSave(formData)
      this.vmList.image = files.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
.search {
  width: 100%;
}
.form {
  padding-top: 10px;
}
.InquireBtn {
  color: #fff;
  border-radius: 4px;
  background-color: #5f84ff;
}
.avatar{
  width: 148px;
  height: 148px;
}
.addBtn {
  color: #fff;
  background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
}
.batchBtn {
  background-color: #fbf4f0 !important;
  color: #655b56 !important;
  border: none;
}
.img {
  display: block;
  width: 24px;
  height: 24px;
  -o-object-fit: cover;
  object-fit: cover;
  border-radius: 50%;
  background: #f3f6fb;
  border: 1px solid #f3f6fb;
}
</style>
